package com.tchcn.supermarket.ui.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fanwe.library.adapter.http.model.SDResponse;
import com.tchcn.library.http.AppRequestCallback;
import com.tchcn.library.model.BaseActModel;
import com.tchcn.library.model.UserInfoModel;
import com.tchcn.library.utils.LogUtil;
import com.tchcn.supermarket.R;
import com.tchcn.supermarket.adapter.BackstageGoodsTypeAdapter;
import com.tchcn.supermarket.base.BaseRecyclerAdapter;
import com.tchcn.supermarket.base.SBaseFragment;
import com.tchcn.supermarket.common.SCommonInterface;
import com.tchcn.supermarket.dao.PendingOrdersModelDao;
import com.tchcn.supermarket.dbmodel.PendingOrderModel;
import com.tchcn.supermarket.model.Good;
import com.tchcn.supermarket.model.GoodInfoActModel;
import com.tchcn.supermarket.model.GoodTypeActModel;
import com.tchcn.supermarket.utils.GlideUtil;
import com.tchcn.supermarket.utils.SDToast;
import com.tchcn.supermarket.utils.ViewBinder;

import java.util.ArrayList;
import java.util.List;

/**
 *  后台管理-商品管理-新增商品
 * Created by humu on 2018/5/28.
 */

public class NewClassificationFragment extends SBaseFragment {

    private EditText et_good_name;
    private EditText et_code_num;
    private TextView tv_type_name;
    private EditText et_unit;
    private EditText et_purchase_price; //进货价
    private TextView et_sale_price;
    private EditText et_vip_price;
    private EditText et_stock_num;
    private EditText et_warning_line;
    private ImageView iv_good_img;

    private static NewClassificationFragment fragment;
    private BackstageGoodsManageFragment parentFragment;
    private BackstageGoodsTypeAdapter typeAdapter;

    private List<GoodTypeActModel.GoodTypeData.GoodType> goodTypeList = new ArrayList<>();
    private int currentGoodTypeIndex = 0;
    private String selectedGoodTypeId = "";
    private String currentGoodId = "";
    private LinearLayout ll_stock_num;
    private TextView tv_operate_title;

    public static NewClassificationFragment getInstance(int cGoodIndex,String sGoodTypeId,String currentGoodId){
        //if(fragment == null){
            fragment = new NewClassificationFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("cGoodIndex",cGoodIndex);
            bundle.putString("sGoodTypeId",sGoodTypeId);
            bundle.putString("currentGoodId",currentGoodId);
            fragment.setArguments(bundle);
        //}
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.sfragment_new_classification;
    }

    @Override
    protected void initView() {
        selectedGoodTypeId = getArguments().getString("sGoodTypeId");
        currentGoodId = getArguments().getString("currentGoodId");
        currentGoodTypeIndex = getArguments().getInt("cGoodIndex");
        initUI();
        initGoodTypes();
    }

    public void initGoodTypes() {
        SCommonInterface.getAllTables(activity.getLocationId(), new AppRequestCallback<GoodTypeActModel>() {
            @Override
            protected void onSuccess(SDResponse sdResponse) {
                if(actModel.isOk()){
                    GoodTypeActModel.GoodTypeData data = actModel.getData();
                    if(data != null){
                        goodTypeList = data.getRes();
                        if(goodTypeList != null && goodTypeList.size()>0){
                            goodTypeList.get(currentGoodTypeIndex).setChecked(true);
                            ViewBinder.setTextView(tv_type_name,goodTypeList.get(currentGoodTypeIndex).getName());
                            typeAdapter.setDatas(goodTypeList);
                        }
                    }
                }
            }
        });
    }

    private void initUI() {
        parentFragment = (BackstageGoodsManageFragment) getParentFragment();
        TextView tv_return = find(R.id.tv_return);
        tv_return.setOnClickListener(this);
        RecyclerView rv_types = find(R.id.rv_types);
        rv_types.setLayoutManager(new LinearLayoutManager(context));
        tv_operate_title = find(R.id.tv_operate_title);
        Button btn_left = find(R.id.btn_left);
        btn_left.setOnClickListener(this);
        Button btn_right = find(R.id.btn_right);
        btn_right.setOnClickListener(this);
        et_good_name = find(R.id.et_good_name);
        et_code_num = find(R.id.et_code_num);
        tv_type_name = find(R.id.tv_type_name);
        et_unit = find(R.id.et_unit);
        et_purchase_price = find(R.id.et_purchase_price);
        et_sale_price = find(R.id.et_sale_price);
        et_vip_price = find(R.id.et_vip_price);
        ll_stock_num = find(R.id.ll_stock_num);
        et_stock_num = find(R.id.et_stock_num);
        et_warning_line = find(R.id.et_warning_line);
        iv_good_img = find(R.id.iv_good_img);

        typeAdapter = new BackstageGoodsTypeAdapter(1);
        typeAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<GoodTypeActModel.GoodTypeData.GoodType>() {
            @Override
            public void onItemClick(View covertView, int position, GoodTypeActModel.GoodTypeData.GoodType data) {
                typeAdapter.getItem(currentGoodTypeIndex).setChecked(false);
                data.setChecked(true);
                ViewBinder.setTextView(tv_type_name,data.getName());
                currentGoodTypeIndex = position;
                typeAdapter.notifyDataSetChanged();
                selectedGoodTypeId = data.getId();
            }
        });
        rv_types.setAdapter(typeAdapter);

        if(TextUtils.isEmpty(currentGoodId)){
            //新增商品
            ViewBinder.setTextView(tv_operate_title,"新增商品资料");
            ViewBinder.setTextView(btn_left,"保存并继续新增");
            btn_left.setTextColor(getResources().getColor(R.color.main_blue));
            ll_stock_num.setVisibility(View.VISIBLE);
            et_stock_num.setVisibility(View.VISIBLE);
        }else{
            //编辑商品
            ViewBinder.setTextView(tv_operate_title,"编辑商品资料");
            ViewBinder.setTextView(btn_left,"删除商品资料");
            btn_left.setTextColor(getResources().getColor(R.color.btn_del_good_info));
            ll_stock_num.setVisibility(View.GONE);
            et_stock_num.setVisibility(View.GONE);
            SCommonInterface.getGoodInfoById(currentGoodId, new AppRequestCallback<GoodInfoActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    LogUtil.e("getGoodInfoById",sdResponse.getResult());
                    if(actModel.isOk()){
                        GoodInfoActModel.GoodInfoByIdData data = actModel.getData();
                        if(data != null){
                            GoodInfoActModel.GoodInfoByIdData.GoodInfoById goodInfo = data.getRes();
                            if(goodInfo != null){
                                String bar_code = goodInfo.getBar_code();
                                ViewBinder.setTextView(et_code_num,bar_code);
                                GlideUtil.load(context,goodInfo.getImage(),iv_good_img);
                                ViewBinder.setTextView(et_good_name,goodInfo.getCate_name());
                                ViewBinder.setTextView(et_unit,goodInfo.getUnit());
                                ViewBinder.setTextView(et_sale_price,goodInfo.getRetail_price());
                                ViewBinder.setTextView(et_vip_price,goodInfo.getUser_price());
                                ViewBinder.setTextView(et_warning_line,goodInfo.getStock_warning());
                                ViewBinder.setTextView(et_purchase_price,goodInfo.getBuy_price());
                            }
                        }
                    }
                }
            });
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if(id == R.id.tv_return){ //返回
            parentFragment.changeFragment(this,GoodsManageFragment.getInstance());
        }else if(id == R.id.btn_right){
            confirm(id);
        }else if(id == R.id.btn_left){
            if("编辑商品资料".equals(tv_operate_title.getText().toString())){
                if(!CashierHomeFragment.getInstance().isInShopcart(currentGoodId)){
                    if(!isPendingOrderhave(currentGoodId)){
                        SCommonInterface.delGood(currentGoodId, new AppRequestCallback<BaseActModel>() {
                            @Override
                            protected void onSuccess(SDResponse sdResponse) {
                                LogUtil.e("delGood",sdResponse.getResult());
                                if(actModel.isOk()){
                                    parentFragment.changeFragment(NewClassificationFragment.this,GoodsManageFragment.getInstance());
                                    GoodsManageFragment.getInstance().getGoodsByType();
                                }
                                SDToast.showToast(context,actModel.getMsg());
                            }
                        });
                    }else{
                        SDToast.showToast(context,"挂单中存在该商品");
                    }
                }else{
                    SDToast.showToast(context,"该商品在购物车中");
                }
            }else{
                confirm(id);
            }
        }
    }

    private boolean isPendingOrderhave(String goodId){
        PendingOrderModel model = PendingOrdersModelDao.queryModel();
        if(model != null){
            List<PendingOrderModel.PendingOrder> orderList = model.getOrder_list();
            if(orderList != null && orderList.size() > 0){
                for(PendingOrderModel.PendingOrder pendingOrder: orderList){
                    List<Good> pendingGoodList = pendingOrder.getGood_list();
                    if(pendingGoodList != null && pendingGoodList.size() > 0){
                        for(Good good: pendingGoodList){
                            if(goodId.equals(good.getId())){
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    private void confirm(final int id) {
        String goodName = et_good_name.getText().toString();
        if(TextUtils.isEmpty(goodName)){
            SDToast.showToast(context,"请输入商品名称");
            return;
        }
        String goodUnit = et_unit.getText().toString();
        if(TextUtils.isEmpty(goodUnit)){
            SDToast.showToast(context,"请输入商品单位");
            return;
        }
        String codeNum = et_code_num.getText().toString();
        String buyPrice = et_purchase_price.getText().toString();
        if(TextUtils.isEmpty(buyPrice)){
            SDToast.showToast(context,"请输入进货价");
            return;
        }
        String retailPrice = et_sale_price.getText().toString();
        if(TextUtils.isEmpty(retailPrice)){
            SDToast.showToast(context,"请输入零售价");
            return;
        }
        String userPrice = et_vip_price.getText().toString();
        if(TextUtils.isEmpty(userPrice)){
            SDToast.showToast(context,"请输入会员价");
            return;
        }
        String stockNum = et_stock_num.getText().toString();
        String stockWarningLine = et_warning_line.getText().toString();
        if(TextUtils.isEmpty(stockWarningLine)){
            SDToast.showToast(context,"请输入库存预警值");
            return;
        }
        if("编辑商品资料".equals(tv_operate_title.getText().toString())){
            SCommonInterface.updateGoodInfo(UserInfoModel.getUser_id(), currentGoodId, goodName,
                    codeNum, selectedGoodTypeId, et_unit.getText().toString(), buyPrice, retailPrice,
                    userPrice, stockWarningLine, new AppRequestCallback<BaseActModel>() {
                        @Override
                        protected void onSuccess(SDResponse sdResponse) {
                            if(actModel.isOk()){
                                if(id == R.id.btn_right){
                                    parentFragment.changeFragment(NewClassificationFragment.this,GoodsManageFragment.getInstance());
                                    GoodsManageFragment.getInstance().getGoodsByType();
                                }
                            }
                            SDToast.showToast(context,actModel.getMsg());
                        }
                    });
        }else if("新增商品资料".equals(tv_operate_title.getText().toString())){
            SCommonInterface.addGood(UserInfoModel.getUser_id(), goodName, codeNum, selectedGoodTypeId, goodUnit,
                    buyPrice, retailPrice, userPrice, stockNum, stockWarningLine, new AppRequestCallback<BaseActModel>() {
                        @Override
                        protected void onSuccess(SDResponse sdResponse) {
                            if(actModel.isOk()){
                                if(id == R.id.btn_right){
                                    parentFragment.changeFragment(NewClassificationFragment.this,GoodsManageFragment.getInstance());
                                    GoodsManageFragment.getInstance().getGoodsByType();
                                }else{
                                    ViewBinder.setTextView(et_code_num,"");
                                    ViewBinder.setTextView(et_good_name,"");
                                    ViewBinder.setTextView(et_unit,"");
                                    ViewBinder.setTextView(et_sale_price,"");
                                    ViewBinder.setTextView(et_vip_price,"");
                                    ViewBinder.setTextView(et_warning_line,"");
                                    ViewBinder.setTextView(et_purchase_price,"");
                                    ViewBinder.setTextView(et_stock_num,"");
                                    GoodsManageFragment.getInstance().getGoodsByType();
                                }
                            }
                            SDToast.showToast(context,actModel.getMsg());
                        }
                    });
        }
    }
}
